package com.powerbank.financecenter.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.powerbank.financecenter.entity.UserAccount;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;

/**
 * 用户账户Mapper接口
 */
@Mapper
public interface UserAccountMapper extends BaseMapper<UserAccount> {

    /**
     * 根据用户ID和账户类型查询账户
     */
    @Select("SELECT * FROM user_account WHERE user_id = #{userId} AND account_type = #{accountType} AND deleted = 0")
    UserAccount findByUserIdAndType(@Param("userId") Long userId, @Param("accountType") String accountType);

    /**
     * 冻结账户金额
     */
    @Update("UPDATE user_account SET frozen_amount = frozen_amount + #{amount}, balance = balance - #{amount}, updated_time = NOW() " +
            "WHERE id = #{accountId} AND balance >= #{amount}")
    int freezeAmount(@Param("accountId") Long accountId, @Param("amount") BigDecimal amount);

    /**
     * 解冻账户金额
     */
    @Update("UPDATE user_account SET frozen_amount = frozen_amount - #{amount}, balance = balance + #{amount}, updated_time = NOW() " +
            "WHERE id = #{accountId} AND frozen_amount >= #{amount}")
    int unfreezeAmount(@Param("accountId") Long accountId, @Param("amount") BigDecimal amount);

    /**
     * 扣减账户余额
     */
    @Update("UPDATE user_account SET balance = balance - #{amount}, total_consume = total_consume + #{amount}, " +
            "last_transaction_time = NOW(), updated_time = NOW() " +
            "WHERE id = #{accountId} AND balance >= #{amount}")
    int deductBalance(@Param("accountId") Long accountId, @Param("amount") BigDecimal amount);

    /**
     * 增加账户余额
     */
    @Update("UPDATE user_account SET balance = balance + #{amount}, total_recharge = total_recharge + #{amount}, " +
            "last_transaction_time = NOW(), updated_time = NOW() " +
            "WHERE id = #{accountId}")
    int addBalance(@Param("accountId") Long accountId, @Param("amount") BigDecimal amount);

    /**
     * 更新账户状态
     */
    @Update("UPDATE user_account SET status = #{status}, updated_time = NOW() WHERE id = #{accountId}")
    int updateAccountStatus(@Param("accountId") Long accountId, @Param("status") String status);
}